package be.scond.cartpool;

import java.io.IOException;
import javax.servlet.http.*;
import be.scond.cartpool.API.GroupApi;
import be.scond.cartpool.API.ShoppingListApi;
import be.scond.cartpool.exceptions.GroupDoesNotExistException;
import be.scond.cartpool.exceptions.OpenShoppingListFoundException;

public class CreateShoppingListServlet extends HttpServlet {
	
	static final long serialVersionUID = 1;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/xml");		

		String groupName = req.getParameter("groupName");		
		String respons = "<data>";	

		try {
			ShoppingListApi.createNewShoppingList(groupName);
			String groupInfoXml = GroupApi.getGroupInfo(groupName);				
			respons += "<succes>a new list was created</succes>";
			respons += groupInfoXml;
		} catch (GroupDoesNotExistException e) {
			respons += "<error>"+groupName+" was not found</error>";
		} catch (OpenShoppingListFoundException e) {
			respons += "<error>There already is an open shoppingList</error>";	
		}
			
		respons += "</data>";

		resp.getWriter().print(respons);
	}
}